# -*- coding: utf-8 -*-
"""User models."""
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
from flask import current_app

from myflaskapp.database import Column, Model, SurrogatePK, db, reference_col, relationship


class User(UserMixin, Model, SurrogatePK):
    __tablename__ = 'users'
    #id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    chinese_name = Column(db.String(10))
    #role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    role_id = reference_col('roles', nullable=True)
    zhiwu = Column(db.String(32))
    bumen = Column(db.String(64))
    sbu_id = reference_col('sbus',nullable=True)

    def __init__(self, username, **kwargs):
        """Create instance."""
        db.Model.__init__(self, username=username, **kwargs)

    @property
    def password(self):
        raise AttributeError('没有权限查看密码！')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    def generate_auth_token(self, expiration):
        s = Serializer(current_app.config['SECRET_KEY'],
                       expires_in=expiration)
        return s.dumps({'id': self.id}).decode('utf-8')

    @staticmethod
    def verify_auth_token(token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return None
        return User.query.get(data['id'])

    def __repr__(self):
        return '<User %r>' % self.username


class Role(Model, SurrogatePK):
    __tablename__ = 'roles'
    #id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    introduction = db.Column(db.String(64))
    users = db.relationship('User', backref='role')

    def __init__(self, name, **kwargs):
        """Create instance."""
        db.Model.__init__(self, name=name, **kwargs)

    def __repr__(self):
        return '<Role %r>' % self.name

class Sbu(Model,SurrogatePK):
    __tablename__ = 'sbus'
    name = Column(db.String(64),unique=True)
    users = relationship('User', backref='sbu')

    def __init__(self, name, **kwargs):
        """Create instance."""
        db.Model.__init__(self, name=name, **kwargs)

    def __repr__(self):
        return '<Sbu %r>' % self.name
